﻿using Newtonsoft.Json.Linq;
using System.Text;

namespace JT809.GpsRedisConsumer.Common
{
    public class SMSUtil
    {
        private static IConfiguration config;

        public static async Task<string> SendCloudMasAsync(string Message, int areaType, params string[] destinationAddresses)
        {
            if (config == null)
            {
                var builder = new ConfigurationBuilder();
                builder.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
                builder.AddJsonFile("appsettings.json", false, true);
                config = builder.Build();
            }
            string CloudMas = "CloudMas";
            switch (areaType)
            {
                case 1:
                    CloudMas = "CloudMasNH";
                    break;
                case 2:
                    CloudMas = "CloudMasXZ";
                    break;
                case 3:
                    CloudMas = "CloudMasJK";
                    break;
                case 4:
                    CloudMas = "CloudMasJS";
                    break;
                case 5:
                    CloudMas = "CloudMasPH";
                    break;
                case 6:
                    CloudMas = "CloudMasHY";
                    break;
                case 7:
                    CloudMas = "CloudMasHN";
                    break;
                case 8:
                    CloudMas = "CloudMasTX";
                    break;
                case 9:
                    CloudMas = "CloudMasGQ";
                    break;
                default:
                    break;
            }
            var url = config[CloudMas + ":Url"];
            var ecName = config[CloudMas + ":EcName"];
            var apId = config[CloudMas + ":ApId"];
            var secretKey = config[CloudMas + ":SecretKey"];
            var sign = config[CloudMas + ":Sign"];
            var addSerial = config[CloudMas + ":AddSerial"];

            var mobiles = string.Join(",", destinationAddresses);
            var content = Message;

            var mac = BitConverter.ToString(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(ecName + apId + secretKey + mobiles + content + sign + addSerial))).Replace("-", "").ToLower();
            var postvalue = Convert.ToBase64String(Encoding.UTF8.GetBytes(JObject.FromObject(new
            {
                ecName,
                apId,
                secretKey,
                mobiles,
                content,
                sign,
                addSerial,
                mac
            }).ToString()));
            return await HttpUtil.PostByteArrayAsync(url, Encoding.UTF8.GetBytes(postvalue));
        }
    }
}
